package biz

import (
	"context"
	"platform-sastay-file/internal/conf"

	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/log"
)

var (
	ErrDomainNameNotFound = errors.NotFound("DOMAIN_NAME_NOT_FOUND", "域名不存在")
)

// DomainNameMap 域名映射信息
type DomainNameMap struct {
	DomainName string // 域名
	IP         string // ip地址
}

type DomainNameRepo interface {
	PutDomain(ctx context.Context, ip, domainName string) error
	GetDomain(ctx context.Context, ip string) (*DomainNameMap, error)
}

type DomainNameUsecase struct {
	log  *log.Helper
	conf *conf.Biz
	repo DomainNameRepo
}

func NewDomainNameUsecase(logger log.Logger, conf *conf.Biz, repo DomainNameRepo) *DomainNameUsecase {
	return &DomainNameUsecase{
		log:  log.NewHelper(log.With(logger, "module", "usecase/domainName")),
		conf: conf,
		repo: repo,
	}
}

// PutDomainNameMap 更新域名映射
func (d *DomainNameUsecase) PutDomainNameMap(ctx context.Context, ip, domainName string) (*DomainNameMap, error) {
	err := d.repo.PutDomain(ctx, ip, domainName)
	if err != nil {
		return nil, err
	}
	return &DomainNameMap{
		DomainName: domainName,
		IP:         ip,
	}, nil
}

// GetDomainName 获取域名信息
func (d *DomainNameUsecase) GetDomainName(ctx context.Context, ip string) (*DomainNameMap, error) {
	return d.repo.GetDomain(ctx, ip)
}
